<template>
	<view>
		<view>

			<view class="padding-sm">
				已选：{{numberOfRecommendations.length}}个
			</view>
			<treeNode ref="treeNodeRef" @ppppp2="ppppp2">
			</treeNode>
			<button @click="submitForm" class="login-btn cu-btn block bg-blue lg round">提交</button>
		</view>
	</view>
</template>

<script>
	import {
		doDelete,
		doDeleteAll,
		doExportExcel,
		doUpdateOutTime,
		getGjzmsById,
		doUpdate,
		getJYPlan,
		doInsert,
		getList,
		getUnfinishedMonthlyPlanInsert
	} from "@/api/lpc/monthlyplan/LpcMonthlyPlanManagementApi";

	import {
		findTreeByid
	} from "@/api/coreLessonPreparation/source";
	import {
		isJson,
		isNull
	} from "../../../utils/validate";

	export default {
		data() {
			return {
				queryFrom: {

				},
				form: {
					JYPlanList: []
				},
				options: [],
				numberOfRecommendations: [],
				numberOfRecommendations: []
			}
		},
		onLoad(op) {
			if (op.id != null) {
				this.queryFrom.id_EQ = op.id
				this.form.name = op.name
				this.init()
			}
		},
		methods: {
			async submitForm() {



				this.form2 = {}
				this.form2.confirmTheName = this.form.name
				this.form2.customerId = this.form.customerId
				this.form2.vipContractId = this.form.vipContractId
				this.form2.monthly = this.form.monthly
				this.form2.id = this.form.id
				this.form2.offlineClassName = this.form.offlineClassName
				this.form2.pdfUrl = this.form.pdfUrl
				this.form2.nlJy = JSON.stringify(this.form.nlJy)
				if (JSON.stringify(this.numberOfRecommendations) != "[]") {
					this.form2.numberOfRecommendations = JSON.stringify(this.numberOfRecommendations)
				}
				// 修改
				if (!isNull(this.form2.id)) {
					var adfasd = JSON.parse(this.form2.numberOfRecommendations)
					for (const adfasdElement of adfasd) {
						adfasdElement.videoUrl = null
						adfasdElement.videoUrl2 = null
					}
					this.form2.numberOfRecommendations = JSON.stringify(adfasd)
					console.log(this.form2)
					const {
						success,
						msg
					} = await doUpdate(this.form2);
					if (success) {
						this.$baseMessage(msg, "success");
					}
				}

			},
			// 查找上级 ID 的函数
			findParentIds(tree, id, parentIds = []) {
				for (const node of tree) {
					if (node.value === id) {
						if (node.parentId !== null) {
							parentIds.push(node.parentId);
						}
						return parentIds; // 找到目标节点，返回当前的 parentIds
					}
					// 递归查找子节点
					if (node.children && node.children.length > 0) {
						const result = this.findParentIds(node.children, id, parentIds);
						if (result.length > 0) {
							if (node.parentId !== null) {
								parentIds.push(node.parentId); // 添加当前节点的 parentId
							}
							return parentIds; // 返回找到的结果
						}
					}
				}
				return parentIds; // 如果没有找到，返回空数组
			},
			ppppp2(e) {
				console.log(e);
				let ids = this.findParentIds(this.options, e.value)
				ids.pop()
				ids.reverse()
				ids.push(e.value)
				e.ids = ids
				if (this.numberOfRecommendations.length == 0) {
					this.numberOfRecommendations.push(e)
					return
				}
				let asdf = false
				for (var i = 0; i < this.numberOfRecommendations.length; i++) {
					if (e.value == this.numberOfRecommendations[i].value) {
						asdf = true
						this.numberOfRecommendations.splice(i, 1)
						return
					}
				}
				if (!asdf) {
					this.numberOfRecommendations.push(e)
				}
			},
			init() {
				//查询合同信息
				this.getJYPlan()
			},

			async update(e) {
				let form2
				form2 = Object.assign({}, this.form);
				if (typeof(this.form.gjzms) != 'string' && this.form.gjzms != null) {
					form2.gjzms = JSON.stringify(this.form.gjzms)
				} else {
					form2.gjzms = this.form.gjzms
				}
				form2.summary = this.form.summary
				if (form2.offlineClassName == "2") {
					form2.nl = JSON.stringify(this.form.nl)
					form2.xw = JSON.stringify(this.form.xw)
				} else {
					form2.nl = JSON.stringify(this.form.nl)
					form2.xw = JSON.stringify(this.form.xw)
				}
				delete form2.JY
				delete form2.JYPlanList
				form2.confirmTheName = this.form.customer.student.name
				form2.izUsable = '1'

				if (form2.id == null) {
					form2.summary = form2.summary + form2.confirmTheName
					let form3 = form2

					const {
						success,
						msg
					} = await doInsert(form3);

					uni.navigateTo({
						url: "/pages/lpc/monthlyplan/index"
					})
				} else {
					let form3 = form2

					const {
						success,
						msg
					} = await doUpdate(form2);
				}

			},

			async getJYPlan(id) {
				await this.getByid()
				await this.getGjzmsById();
				const {
					data
				} = await getJYPlan({
					id: this.queryFrom.id_EQ
				});
				this.form.JYPlanList = data

				this.getTree()
			},
			addIsOpenProperty(tree) {
				tree.forEach(node => {
					node.select = false; // 添加 isopen 属性并设置为 false

					for (let s of this.form.JYPlanList) {

						let asdfasd = JSON.parse(s.ids);


						if (asdfasd[asdfasd.length - 1] == node.value) {
							console.log('成功');
							console.log(node.value);
							node.select = true
							this.numberOfRecommendations.push(s)
						}
					}

					node.isopen = false; // 添加 isopen 属性并设置为 false
					if (node.children != null && node.children.length > 0) {
						this.addIsOpenProperty(node.children); // 递归处理子节点
					}
				});
			},
			buildTree(data) {
				const root = {
					children: []
				};

				data.forEach(item => {
					const parts = item.table.split('/').map(part => part.trim());
					let currentNode = root;

					parts.forEach(part => {
						// 查找当前节点的子节点
						let existingNode = currentNode.children.find(child => child.table === part);

						// 如果不存在，则创建新节点
						if (!existingNode) {
							existingNode = {
								table: part,
								children: []
							};
							currentNode.children.push(existingNode);
						}

						// 更新当前节点为找到的子节点
						currentNode = existingNode;
					});
				});

				return root.children; // 返回根节点的子节点
			},

			async getGjzmsById() {
				const {
					data,
					msg,
					success
				} = await getGjzmsById({
					id: this.queryFrom.id_EQ
				})
				if (isJson(data.gjzms)) {
					this.form.gjzms = JSON.parse(data.gjzms)
				} else {
					//最老的月计划 不支持修改
					this.form.gjzms = data.gjzms
					this.form.gjzms = this.form.replace(/\n/g, "huannhang");
					this.form.gjzms = this.form.split("huannhang");
				}
			},

			async getByid() {
				const {
					data
				} = await getList(this.queryFrom);
				if (!isNull(data)) {
					this.form = data.rows[0]
					this.form.name = data.rows[0].customer.student.name
					this.form.phone = data.rows[0].customer.student.name
				}

			},

			async getTree() {
				// 来源树
				let parentId = "000";
				if (this.form.offlineClassName == '5' || this.form.offlineClassName == '3' || this.form
					.offlineClassName == '13') {
					parentId = "1556972739719798785";
					this.studentsfkeyi2 = true
					this.studentsfkeyi = false


					const {
						data
					} = await findTreeByid({
						"parentId": parentId
					});
					this.options = data
				} else if (this.form.offlineClassName == '4' || this.form.offlineClassName == '12') {
					parentId = "1562355016004575233";
					this.studentsfkeyi2 = true
					this.studentsfkeyi = false
					const {
						data
					} = await findTreeByid({
						"parentId": parentId
					});
					this.options = data
				} else {

					this.$notify({
						title: '警告',
						message: '没有这个课程对应的教研点选项目',
						type: 'warning'
					});

					this.studentsfkeyi2 = false
					this.studentsfkeyi = true

					parentId = "000";
				}


				// this.form.JYPlanList = this.buildTree(this.form.JYPlanList)

				this.addIsOpenProperty(this.options)


				for (let s of this.options) {
					s.is_level = 1
				}

				this.$refs.treeNodeRef.list = this.options
				this.form.JY = data

			},
		}
	}
</script>

<style>

</style>